<script setup>
import { getDetail } from '@/apis/detail'
import { useRoute } from 'vue-router'
import { useCartStore } from "@/stores/cartStore";
import { useUserStore } from "@/stores/userStore";
import { useFavoriteStore } from '@/stores/favoriteStore';
import { useHistoryStore } from '@/stores/historyStore';
import { ElMessage } from "element-plus";
import 'element-plus/theme-chalk/el-message.css'
const goods = ref({})
const route = useRoute()
const historyStore = useHistoryStore();
const getGoods = async () => {
  const res = await getDetail(route.params.id)
  goods.value = res.data
  addHistory()
}
onMounted(() => getGoods())

const cartStore = useCartStore();
const userStore = useUserStore();
const favoriteStore = useFavoriteStore();

const addHistory = () => {
  //如果有相同的，则删除再添加
  if (historyStore.historyList.findIndex(item => String(item.productId) === String(route.params.id)) > -1) {
    historyStore.delHistory(userStore.userInfo.userId, route.params.id)
    console.log('已有商品，删除再添加');
    //等待
    setTimeout(() => {
      historyStore.addHistory({
        userId: userStore.userInfo.userId,
        productId: route.params.id
      })
    }, 1000);

  } else {
    historyStore.addHistory({
      userId: userStore.userInfo.userId,
      productId: route.params.id
    })
  }
}

//定义购买数量最小为1
const count = ref(1);

//添加购物车
const addCart = () => {
  if (cartStore.cartList.findIndex(item => String(item.productId) === String(route.params.id)) > -1) {
    console.log('已有商品');
    // 获取现有商品的数量，并增加新的数量
    const existingQuantity = cartStore.cartList[cartStore.cartList.findIndex(item => String(item.productId) === String(route.params.id))].quantity;
    const newQuantity = existingQuantity + count.value;
    console.log(newQuantity);
    cartStore.updateCart(
      userStore.userInfo.userId,
      route.params.id,
      newQuantity,
    )
  } else {
    console.log('无商品');
    cartStore.addCart({
      userId: userStore.userInfo.userId,
      productId: route.params.id,
      quantity: count.value,
    })
    console.log(cartStore.cartList);
  }
}

//收藏
const addFavorite = () => {
  if (favoriteStore.favoriteList.findIndex(item => String(item.productId) === String(route.params.id)) > -1) {
    console.log('已收藏');
    favoriteStore.delFavorite(userStore.userInfo.userId, route.params.id)
  } else {
    console.log('未收藏');
    favoriteStore.addFavorite({
      userId: userStore.userInfo.userId,
      productId: route.params.id,
    })
  }
}

</script>

<template>
  <div class="xtx-goods-page">
    <div class="container">
      <div class="bread-container" v-if="goods.details">
        <el-breadcrumb separator=">">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <!--
                错误原因：goods一开始{}  {}.categories -> undefined  -> undefined[1]
                1. 可选链的语法?.
                2. v-if手动控制渲染时机 保证只有数据存在才渲染
            -->
          <el-breadcrumb-item :to="{ path: `/category/${goods.categories[1].id}` }">{{ goods.categories[1].name }}
          </el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: `/category/sub/${goods.categories[0].id}` }">
            {{ goods.categories[0].name }}
          </el-breadcrumb-item>
          <el-breadcrumb-item>{{ goods.productName }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- 商品信息 -->
      <div class="info-container">
        <div>
          <div class="goods-info">
            <div class="media">
              <!-- 图片预览区 -->
              <div class="goods-image">
                <!-- 左侧大图-->
                <div class="middle">
                  <img :src="goods.productImage" alt="商品图片" />
                </div>
              </div>
              <!-- <imageView :image-list="goods.productImage" /> -->
              <!-- <imageView :image-list="goods.productImage"/> -->
              <!-- 统计数量 -->
              <ul class="goods-sales">
                <li>
                  <p>销量人气</p>
                  <p> {{ goods.sales }}+ </p>
                  <p><i class="iconfont icon-task-filling"></i>销量人气</p>
                </li>
                <li>
                  <p>商品评价</p>
                  <p>{{ goods.commentCount }}+</p>
                  <p><i class="iconfont icon-comment-filling"></i>查看评价</p>
                </li>
                <li>
                  <p>收藏人气</p>
                  <p>{{ goods.collectCount }}+</p>
                  <!-- 已收藏则显示取消收藏 -->
                  <p @click="addFavorite"
                    v-if="favoriteStore.favoriteList.findIndex(item => String(item.productId) === String(route.params.id)) > -1">
                    <i class="iconfont icon-favorite-filling"></i>取消收藏</p>
                  <p @click="addFavorite" v-else><i class="iconfont icon-favorite-filling"></i>收藏商品</p>
                </li>
              </ul>
            </div>
            <div class="spec">
              <!-- 商品信息区 -->
              <p class="g-name"> {{ goods.productName }} </p>
              <p class="g-desc">{{ goods.brandName }} </p>
              <p class="g-price">
                <span> {{ goods.unitPrice }}</span>
                <span>{{ goods.unitPrice }}</span>
              </p>
              <p class="g-desc">库存剩余：{{ goods.stock }} </p>
              <div class="g-service">
                <dl>
                  <dt>促销</dt>
                  <dd>{{ goods.discountName }}</dd>
                </dl>
                <dl>
                  <dt>服务</dt>
                  <dd>
                    <span>无忧退货</span>
                    <span>快速退款</span>
                    <span>免费包邮</span>
                    <a href="javascript:;">了解详情</a>
                  </dd>
                </dl>
              </div>
              <!-- 商品颜色 -->
              <div class="g-color">颜色：{{ goods.productColor }}</div>
              <!-- 商品尺寸 -->
              <div class="g-size">尺寸：{{ goods.productSize }}</div>

              <!-- 数据组件 -->
              <el-input-number v-model="count" :min="1" />
              <!-- 按钮组件 -->
              <div>
                <el-button size="large" class="btn" @click="addCart">
                  加入购物车
                </el-button>
              </div>

            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>


<style scoped lang='scss'>
.xtx-goods-page {
  .goods-info {
    min-height: 600px;
    background: #fff;
    display: flex;

    .media {
      width: 580px;
      height: 600px;
      padding: 30px 50px;

      .goods-image {
        width: 480px;
        height: 400px;
        position: relative;
        display: flex;

        .middle {
          width: 400px;
          height: 400px;
          background: #f5f5f5;
        }
      }
    }

    .spec {
      flex: 1;
      padding: 30px 30px 30px 0;
    }
  }

  .goods-footer {
    display: flex;
    margin-top: 20px;

    .goods-article {
      width: 940px;
      margin-right: 20px;
    }

    .goods-aside {
      width: 280px;
      min-height: 1000px;
    }
  }

  .goods-tabs {
    min-height: 600px;
    background: #fff;
  }

  .goods-warn {
    min-height: 600px;
    background: #fff;
    margin-top: 20px;
  }

  .number-box {
    display: flex;
    align-items: center;

    .label {
      width: 60px;
      color: #999;
      padding-left: 10px;
    }
  }

  .g-name {
    font-size: 22px;
  }

  .g-desc {
    color: #999;
    margin-top: 10px;
  }

  .g-price {
    margin-top: 10px;

    span {
      &::before {
        content: "¥";
        font-size: 14px;
      }

      &:first-child {
        color: $priceColor;
        margin-right: 10px;
        font-size: 22px;
      }

      &:last-child {
        color: #999;
        text-decoration: line-through;
        font-size: 16px;
      }
    }
  }

  .g-service {
    background: #f5f5f5;
    width: 500px;
    padding: 20px 10px 0 10px;
    margin-top: 10px;

    dl {
      padding-bottom: 20px;
      display: flex;
      align-items: center;

      dt {
        width: 50px;
        color: #999;
      }

      dd {
        color: #666;

        &:last-child {
          span {
            margin-right: 10px;

            &::before {
              content: "•";
              color: $xtxColor;
              margin-right: 2px;
            }
          }

          a {
            color: $xtxColor;
          }
        }
      }
    }
  }

  .g-color {
    margin-top: 10px;
    border: 1px solid #ddd;
    /* 外边框 */
    padding: 10px;
    border-radius: 4px;
    /* 圆角 */
    flex: 1;
    max-width: max-content;
  }

  .g-size {
    margin-top: 10px;
    border: 1px solid #ddd;
    /* 外边框 */
    padding: 10px;
    border-radius: 4px;
    /* 圆角 */
    flex: 1;
    max-width: max-content;
    margin-bottom: 20px;
  }

  .goods-sales {
    display: flex;
    width: 400px;
    align-items: center;
    text-align: center;
    height: 140px;

    li {
      flex: 1;
      position: relative;

      ~li::after {
        position: absolute;
        top: 10px;
        left: 0;
        height: 60px;
        border-left: 1px solid #e4e4e4;
        content: "";
      }

      p {
        &:first-child {
          color: #999;
        }

        &:nth-child(2) {
          color: $priceColor;
          margin-top: 10px;
        }

        &:last-child {
          color: #666;
          margin-top: 10px;

          i {
            color: $xtxColor;
            font-size: 14px;
            margin-right: 2px;
          }

          &:hover {
            color: $xtxColor;
            cursor: pointer;
          }
        }
      }
    }
  }
}

.goods-tabs {
  min-height: 600px;
  background: #fff;

  nav {
    height: 70px;
    line-height: 70px;
    display: flex;
    border-bottom: 1px solid #f5f5f5;

    a {
      padding: 0 40px;
      font-size: 18px;
      position: relative;

      >span {
        color: $priceColor;
        font-size: 16px;
        margin-left: 10px;
      }
    }
  }
}

.goods-detail {
  padding: 40px;

  .attrs {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 30px;

    li {
      display: flex;
      margin-bottom: 10px;
      width: 50%;

      .dt {
        width: 100px;
        color: #999;
      }

      .dd {
        flex: 1;
        color: #666;
      }
    }
  }

  >img {
    width: 100%;
  }
}

.btn {
  margin-top: 20px;

}

.bread-container {
  padding: 25px 0;
}
</style>